package v1

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/web/middleware"
	"zimuzu_cvn_web_api/service"
)

type PassportAPI struct {
}

func (passport PassportAPI) Name() string {
	return "passport API"
}

func (passport PassportAPI) Bind() {
	passportAPI := config.C.Router.Group("/v1/passport", middleware.TrackLog())
	{
		passportAPI.POST("login", login)
		passportAPI.POST("reg", reg)
		passportAPI.POST("loginOut", loginOut)
	}
	passport2API := config.C.Router.Group("/v1/passport", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		passport2API.GET("loginCheck", loginCheck)
	}
}

type loginParams struct {
	Account string `form:"account" json:"account" binding:"required"`
	Pwd     string `form:"pwd" json:"pwd" binding:"required"`
	Area    int    `form:"area" json:"area" binding:"required"`
}

//登录提交
//Auth: Xu
func login(c *gin.Context) {
	var params loginParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if !IsPhone(params.Account) {
		api.SendResponse(c, errors.New("请输入正确格式的手机号"), nil)
		return
	}
	loginIp := c.ClientIP()
	var user model.User
	user, checkloginErr := service.CheckLogin(params.Account, params.Pwd, params.Area)
	if checkloginErr != nil {
		if user.Uid != 0 {
			service.AddLoginErrCount(loginIp, user.Uid)
		}
		api.SendResponse(c, checkloginErr, nil)
		return
	}
	//检验是否已设置支付密码
	hasPayPassword := 1
	if res, err := service.CheckPayPasswordExist(user.Uid); err == nil && res {
		hasPayPassword = 2
	}

	token := service.CreateToken(service.LoginPlatformPc, user.Uid, user.Password, user.Nickname)
	shopToken := service.GetShopTokenCache(user.Uid)
	responseData := map[string]interface{}{
		"uid":            user.Uid,
		"hasPayPassword": hasPayPassword,
		"shop_token":     shopToken,
		"token":          token,
	}

	errno.OK.Info = "用户登录成功"
	api.SendResponse(c, errno.OK, responseData)
	return

}

//登录检查
//Auth: Xu
func loginCheck(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	userInfo, err := service.GetUserInfo(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	//nickName,_ := service.GetUserInfoFiled(userId.(int64), "nickname")
	//mobile,_ := service.GetUserInfoFiled(userId.(int64), "PhoneNumber")
	responseData := map[string]string{
		"nickname": userInfo.Nickname,
		"mobile":   userInfo.PhoneNumber,
	}
	api.SendResponse(c, errno.OK, responseData)
	return
}

type regParams struct {
	Mobile    string `form:"mobile" json:"mobile" binding:"required"`
	Pwd       string `form:"pwd" json:"pwd" binding:"required"`
	Pwdconfrm string `form:"pwdconfirm" json:"pwdconfirm" binding:"required"`
	Sign      string `form:"sign" json:"sign" binding:"required"`
	NickName  string `form:"nickname" json:"nickname" binding:"required"`
	Area      int    `form:"area" json:"area"`
}

//注册提交
//Auth: Xu
func reg(c *gin.Context) {
	var params regParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	//if errValid := service.ValidateCode(params.Mobile , service.SendCodeSceneReg, params.Code); errValid != nil{
	//	api.SendResponse(c, errValid, nil)
	//	return
	//}
	//验证签名
	if err := service.ValidateRegSign(params.Mobile, params.Sign); err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	_, errCreate := service.Register(params.Mobile, params.Area, params.Pwd, params.Pwdconfrm, params.NickName, c.ClientIP(), 16)
	if errCreate != nil {
		api.SendResponse(c, errCreate, nil)
		return
	}

	errno.OK.Info = "注册成功"
	api.SendResponse(c, errno.OK, nil)
	return

}

type loginOutParams struct {
	Uid   int64  `form:"uid" json:"uid" binding:"required"`
	Token string `form:"token" json:"token" binding:"required"`
}

//退出登录
//Auth: Xu
func loginOut(c *gin.Context) {
	var params loginOutParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err = service.LoginOutClearToken(uid, service.LoginPlatformPc)
	if err != nil {
		api.SendResponse(c, errors.New("退出登录失败"), nil)
		return
	}

	errno.OK.Info = "退出登录成功"
	api.SendResponse(c, errno.OK, nil)
	return
}
